package cn.skyclass.net
{
	import cn.skyclass.business.PagerStatus;
	import cn.skyclass.events.LoadEvent;
	import cn.skyclass.events.PagerEvent;
	import cn.skyclass.events.WsEvent;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	
	/**
	 * 提供分页控制的数据加载器
	 */
	[Bindable]
	public class BasePaginaryLoader extends BaseLoader
	{
		/**
		 * 
		 * @param pageSize 此加载器使用的每页记录数（分页大小），
		 * 	若此值 <= 0 则使用 PagerStatus.DEFAULT_PAGE_SIZE
		 */		
		public function BasePaginaryLoader(pageSize:int=-1)
		{
			this.pageSize = (pageSize > 0) ? pageSize : PagerStatus.DEFAULT_PAGE_SIZE;
			this.initStatus(-1);
		}

		/**
		 * 记录当前的分页状态
		 */
		public var status:PagerStatus;
		
		/**
		 * 是否启用分页功能
		 */
		public var pageEnabled:Boolean = true;
		
		/**
		 * 此加载器使用的每页记录数
		 */		
		protected var pageSize:int;
		
		/**
		 * 全部记录的列表，只有启用历史缓存时才保存全部的已加载的记录
		 */		
		protected var allRecordsList:ArrayCollection = new ArrayCollection();
		
		/**
		 * 是否启用历史缓存，即保存已加载过的记录
		 */		
		public var historyEnabled:Boolean;
		
		/**
		 * 符合条件的记录总数
		 */
		public var totalRecordCount:int;
		
		
		/**
		 * 初始化分页状态控制器。若实例不存在则创建实例，否则仅更新其状态
		 * @param totalRecordCount
		 */		
		protected function initStatus(totalRecordCount:int):void{
			if(!this.status){
				this.status = new PagerStatus();
				this.status.updateStatus(totalRecordCount, this.pageSize);
				this.status.addEventListener(PagerEvent.PAGE_CHANGED, onPageChanged);			
			}else{
				this.status.updateStatus(totalRecordCount, this.pageSize);
			}
		}

		override protected function reset():void{
			super.reset();
			this.initStatus(this.status.totalRecordCount);
			this.pageEnabled = true;
			this.allRecordsList = new ArrayCollection();
			this.historyEnabled = false;
			this.totalRecordCount = 0;
		}
		
		override protected function dispatchLoadedEvent(e:Event=null):void{
			//this.loaded = true;
			this.loading = false;
			this.dataExpired = false;
			
			var we:WsEvent = e as WsEvent;
			if(we != null){
				this.resultList = we.beansCollection;
			}
			dispatchEvent(new LoadEvent(LoadEvent.LOADED));
		}
		
		/**
		 * 根据每页的加载结果来更新分页器和此加载器的状态，不进行其他的数据操作
		 * @param result
		 */		
		protected function updateStatusByPagedResult(result:ArrayCollection):void{
			if(pageEnabled){
				var isLastPage:Boolean = this.status.checkForLastPage(
					result.length, status.currentPageIndex);
				if(this.status.totalRecordCount > 0){
					this.totalRecordCount = this.status.totalRecordCount;
				}
			}else{
				this.status.updateStatus(result.length, result.length);
				this.totalRecordCount = result.length;
			}
		}
		
		/**
		 * 分页状态改变时的操作，即开始加载数据
		 * @param e
		 */		
		protected function onPageChanged(e:Event=null):void{
			this.load();
		}
	}
}